package com.gide;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.google.gson.Gson;

import spark.ModelAndView;
import spark.Spark;
import spark.template.thymeleaf.ThymeleafTemplateEngine;

public class Application {
	
	private final static Logger logger = LoggerFactory.getLogger(Application.class);

	public static void main(String[] args) {
		
		String configFilePath = "application.properties";
		
		for(String str:args) {
			if (str.startsWith("--config.file")) {
				configFilePath = str.split("=")[1];
			}
		}
		
		//获取配置信息
		Properties properties = new Properties();
		try {
			properties.load(new FileInputStream(new File(configFilePath)));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("读取配置信息失败",e);
			System.exit(1);
		} 
		
		//初始化用户数据
		String userStr = properties.getProperty("users");
		Map<String,String> users  = new Gson().fromJson(userStr, Map.class);
				
		//oss config test
		OSSConfig ossConfig = new OSSConfig();
		ossConfig.setAccessKeyId(properties.getProperty("oss.accessKeyId"));
		ossConfig.setAccessKeySecret(properties.getProperty("oss.accessKeySecret"));
		ossConfig.setBucket(properties.getProperty("oss.bucket"));
		ossConfig.setEndpoint(properties.getProperty("oss.setEndpoint"));
		ossConfig.setPrivateImageBaseUrl(properties.getProperty("oss.privateImageBaseUrl"));
		ossConfig.setPublicBucket(properties.getProperty("oss.publicBucket"));
		ossConfig.setPublicBucketEnv(properties.getProperty("oss.publicBucketEnv"));
		ossConfig.setPublicImageBaseUrl(properties.getProperty("oss.publicImageBaseUrl"));
		
		OSSUtil ossUtil = new OSSUtil();
		ossUtil.setOssConfig(ossConfig);
		
		//指定端口
		Spark.port(Integer.parseInt(properties.getProperty("server.port")));
		//指定静态文件路径
		Spark.staticFiles.location("/static");
		
		Spark.get("/", (request, response) -> {
			Map<String, Object> model = new HashMap<>();
		    return new ThymeleafTemplateEngine().render(
		        new ModelAndView(model, "index")
		    );
		});

		//登录接口
		Spark.post("/login",(request, response) -> {

			Map<String,Object> resultMap = new HashMap<>();

			String password = request.queryParams("password");
			if (password == null || password.length() == 0){
				resultMap.put("code", "10001");
				resultMap.put("message", "请输入密码");
				return resultMap;
			}

			String username = users.get(password);
			if(username == null) {
				resultMap.put("code", "10002");
				resultMap.put("message", "密码无效");
				return resultMap;
			}

			request.session().attribute("user", username);

			resultMap.put("code", "10000");
			resultMap.put("message", "登录成功");
			return resultMap;

		},new JsonTransformer());
		
		//查询图片接口
		Spark.get("/image/query",(request, response) -> {
			
			Map<String, Object> model = new HashMap<>();

			String username = request.session().attribute("user");
			if (username == null || username.length() == 0) {
				response.redirect("../");
			}
			
		    return new ThymeleafTemplateEngine().render(
		        new ModelAndView(model, "query")
		    );
		});
		
		//查询图片接口
		Spark.post("/image/query",(request, response) -> {
			
			Map<String, Object> model = new HashMap<>();
			
			String username = request.session().attribute("user");
			if (username == null || username.length() == 0) {
				response.redirect("../");
			}
			
			//两个参数不能同时存在
			String imageId = request.queryParams("imageId");
			String payOrderId = request.queryParams("payOrderId");
			if (imageId == null && payOrderId == null) {
				model.put("code", 10000);
			    return new ThymeleafTemplateEngine().render(
			        new ModelAndView(model, "query")
			    );
			}
			
			//配置数据源
			String driverName = properties.getProperty("datasource1.driverName");
			String dbUrl = properties.getProperty("datasource1.url");
			String dbUsername = properties.getProperty("datasource1.username");
			String dbPassword = properties.getProperty("datasource1.password");
			
			DriverManagerDataSource dataSource = new DriverManagerDataSource();
          	dataSource.setDriverClassName(driverName);
          	dataSource.setUrl(dbUrl);
          	dataSource.setUsername(dbUsername);
          	dataSource.setPassword(dbPassword);
          	
			JdbcTemplate jdbcTemplate = new JdbcTemplate();
			jdbcTemplate.setDataSource(dataSource);
			
			//从数据库查询数据
			Map<String,Object> imageItemMap = null;
			Map<String, Object> orderFormMap = null;
			if (imageId != null && imageId.length() != 0) {
				//通过图片ID查询
				String sql = "select * from image_item where image_id = ?";
				String[] params = {imageId};
				try {
					imageItemMap = jdbcTemplate.queryForMap(sql,params);
					
					System.out.println(imageItemMap.get("image_id"));
					
					model.put("image", imageItemMap);
				} catch (DataAccessException e) {
					logger.error(e.getMessage(),e);
					model.put("code", "10005");
					model.put("message", "图片不存在");
					return new ThymeleafTemplateEngine().render(
				        new ModelAndView(model, "query")
				    );
				}
				
				try {
					//查询订单信息
					String imageItemId = (String)imageItemMap.get("id");
					sql = "select * from order_form where image_item_id = ?";
					String[] params1 = {imageItemId};
					orderFormMap = jdbcTemplate.queryForMap(sql,params1);
					
					model.put("order", orderFormMap);
				} catch (Exception e) {
					
				}
				

			} else if (payOrderId != null && payOrderId.length() != 0) {
				//通过支付订单号查询
				String sql = "select * from order_form where pay_order_id = ?";
				String[] params = {payOrderId};
				try {
					orderFormMap = jdbcTemplate.queryForMap(sql,params);
					
					model.put("order", orderFormMap);
				} catch (DataAccessException e) {
					logger.error(e.getMessage(),e);
					model.put("code", "10005");
					model.put("message", "图片订单不存在");
					return new ThymeleafTemplateEngine().render(
				        new ModelAndView(model, "query")
				    );
				}
				
				try {
					//查询订单信息
					String imageItemId = (String)orderFormMap.get("image_item_id");
					sql = "select * from image_item where id = ?";
					String[] params1 = {imageItemId};
					imageItemMap = jdbcTemplate.queryForMap(sql,params1);
					
					model.put("image", imageItemMap);
				} catch (Exception e) {
					
				}

			} else {
				model.put("code", "10004");
				model.put("message", "参数错误");
				return new ThymeleafTemplateEngine().render(
			        new ModelAndView(model, "query")
			    );
			}
			
			//查询审核数据
			//配置数据源
			driverName = properties.getProperty("datasource2.driverName");
			dbUrl = properties.getProperty("datasource2.url");
			dbUsername = properties.getProperty("datasource2.username");
			dbPassword = properties.getProperty("datasource2.password");
			
			dataSource = new DriverManagerDataSource();
			dataSource.setDriverClassName(driverName);
			dataSource.setUrl(dbUrl);
			dataSource.setUsername(dbUsername);
			dataSource.setPassword(dbPassword);
          	
			JdbcTemplate jdbcTemplate1 = new JdbcTemplate();
			jdbcTemplate1.setDataSource(dataSource);
			
			String sql = "select * from verify_record where image_item_id = ?";
			String imageItemId = (String)imageItemMap.get("id");
			String[] params = {imageItemId};
			List<Map<String,Object>> records = jdbcTemplate1.queryForList(sql, params);
			model.put("verify", records);
			
//			imageItemMap.put("create_time", simpleDateFormat.format(imageItemMap.get("create_time")));
//			imageItemMap.put("verify_time", simpleDateFormat.format(imageItemMap.get("verify_time")));
//			imageItemMap.put("package_time", simpleDateFormat.format(imageItemMap.get("package_time")));
//			orderFormMap.put("pay_time", simpleDateFormat.format(orderFormMap.get("pay_time")));
			
			
			
			
			//获取图片路径
			if (imageItemMap.get("type").equals("INDIVIDUAL")) {
				//自定义图片
				imageItemMap.put("image_path", ossUtil.getObjectUrl((String)imageItemMap.get("object_name"), 50, 30));
			} 
			
			//记录日志
			logger.info("用户{}查询了图片,imageId:{},payOrderId:{}");
			
			model.put("code", "10000");
			model.put("message", "success");
			return new ThymeleafTemplateEngine().render(
		        new ModelAndView(model, "query")
		    );
			
		});
	}
}
